package com.block.datapush.service.apipush;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.YouXinAesUtils;
import com.block.datapush.service.apipush.utils.YouXinUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 80 有信
 */
@Service
public class YouXinPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String phone = memberSourceInfo.getMobile();

        Map<Object, Object> bizMap = new HashMap<>();
        bizMap.put("phone", phone);
        bizMap.put("channelCode", pushApiKeyParam.getApiCode());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("loanMoney", YouXinUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanExpiresMonth", 12);
        bizMap.put("profession", YouXinUtil.getprofession(memberSourceInfo.getGongzuo()));//职业
        bizMap.put("incomeMonth", YouXinUtil.getshouru(memberSourceInfo.getShouru()));
        bizMap.put("payoffType", 10);
        bizMap.put("workingYears", 30);
        bizMap.put("gjjScop", YouXinUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("sbScop", YouXinUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("house", YouXinUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", YouXinUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("baodanScop", YouXinUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("sesameScore", YouXinUtil.getZhimaScore(memberSourceInfo.getZhima()));

        String jsonString = JSON.toJSONString(bizMap);

        String aesKey = YouXinAesUtils.generateAESKey();
        String content = YouXinAesUtils.encryptData(jsonString, aesKey);

        String rsaPublicKey = pushApiKeyParam.getPubKey();
        String key = YouXinAesUtils.encryptKey(rsaPublicKey, aesKey);

        Map<String, Object> bizmMap = new HashMap<>();
        bizmMap.put("content", content);
        bizmMap.put("key", key);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", Base64.encode(JSON.toJSONString(bizmMap)));

        log.info("【有信】撞库开始【queryUrl】{}【bizMap】{}", queryUrl, JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .form(paramMap)
                .execute().body();
        log.info("【有信】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code + "|" + message);
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "10000")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<Object, Object> bizMap = new HashMap<>();
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("realName", memberSourceInfo.getRealname());
        bizMap.put("channelCode", pushApiKeyParam.getApiCode());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("loanMoney", YouXinUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanExpiresMonth", 12);
        bizMap.put("profession", YouXinUtil.getprofession(memberSourceInfo.getGongzuo()));//职业
        bizMap.put("incomeMonth", YouXinUtil.getshouru(memberSourceInfo.getShouru()));
        bizMap.put("payoffType", 10);
        bizMap.put("workingYears", 30);
        bizMap.put("gjjScop", YouXinUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("sbScop", YouXinUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("house", YouXinUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", YouXinUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("baodanScop", YouXinUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("sesameScore", YouXinUtil.getZhimaScore(memberSourceInfo.getZhima()));


        String jsonString = JSON.toJSONString(bizMap);

        String aesKey = YouXinAesUtils.generateAESKey();

        String content = YouXinAesUtils.encryptData(jsonString, aesKey);

        String rsaPublicKey = pushApiKeyParam.getPubKey();
        String key = YouXinAesUtils.encryptKey(rsaPublicKey, aesKey);

        Map<String, Object> bizmMap = new HashMap<>();
        bizmMap.put("content", content);
        bizmMap.put("key", key);


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", Base64.encode(JSON.toJSONString(bizmMap)));

        log.info("【有信】导单开始【requestUrl】{}【bizMap】{}", requestUrl, JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .form(paramMap)
                .execute().body();
        log.info("【有信】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");


        pushApiResult.setCode(code + "|" + message);
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "10000")) {
            String data = resultObject.getString("data");
            pushApiResult.setApproveUrl(data);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.WAIT_QUERY.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());

        String requestUrl = pushApiKeyParam.getQueryUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone", pushQueryParam.getMobile());
        bizMap.put("channelCode",Integer.valueOf(pushApiKeyParam.getApiCode()));

        String jsonString = JSON.toJSONString(bizMap);

        String aesKey = YouXinAesUtils.generateAESKey();

        String content = YouXinAesUtils.encryptData(jsonString, aesKey);

        String rsaPublicKey = pushApiKeyParam.getPubKey();
        String key = YouXinAesUtils.encryptKey(rsaPublicKey, aesKey);

        Map<String, Object> bizmMap = new HashMap<>();
        bizmMap.put("content",content);
        bizmMap.put("key",key);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", Base64.encode(JSON.toJSONString(bizmMap)));

        log.info("【有信】查询开始【requestUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .form(paramMap)
                .execute().body();
        log.info("【有信】查询结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code + "|" + message);
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "10000")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }
}
